<template>
  <div>
    <!--面包屑导航区-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <el-alert title="注意：只允许为第三级分类设置相关属性" type="warning" :closable="false" show-icon></el-alert>
      <el-row class="cate-opt">
        <el-col>
          <span>选择商品分类：</span>
          <el-cascader
            v-model="selectedKeys"
            :props="cateProps"
            :options="cateList"
            @change="handleChange"
          ></el-cascader>
        </el-col>
      </el-row>
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="showDialog()">添加参数</el-button>
          <el-table :data="manyDataList" border>
            <el-table-column type="expand">
               <template slot-scope="scope">
                <el-tag :key="index" v-for="(item,index) in scope.row.attr_vals" closable @close="deleteTag(index,scope.row)">
                  {{item}}
                </el-tag>
                <el-input v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput" size="small"
                @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)" class="tag-input">
                </el-input>
                <el-button v-else size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button size="mini" type="primary" icon="el-icon-edit" @click="editDialog(scope.row.attr_id)">编辑</el-button>
                <el-button size="mini" type="danger" icon="el-icon-delete" @click="removeParam(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="showDialog()">添加属性</el-button>
          <el-table :data="onlyDataList" border>
            <el-table-column type="expand">
               <template slot-scope="scope">
                <el-tag :key="index" v-for="(item,index) in scope.row.attr_vals" closable @close="deleteTag(index,scope.row)">
                  {{item}}
                </el-tag>
                <el-input v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput" size="small"
                @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)" class="tag-input">
                </el-input>
                <el-button v-else size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button size="mini" type="primary" icon="el-icon-edit" @click="editDialog(scope.row.attr_id)">编辑</el-button>
                <el-button size="mini" type="danger" icon="el-icon-delete" @click="removeParam(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加对话框 -->
    <!-- 动态属性和静态属性公用同一个对话框 -->
    <el-dialog :title="'添加' + titleText" :visible.sync="addDialogVisible" width="30%" @close="addDialogClose()">
      <el-form :model="addForm" ref="addFormRef" label-width="100px">
        <el-form-item label="参数名称：" prop="attr_name">
          <el-input type="text" v-model="addForm.attr_name" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑对话框 -->
    <el-dialog :title="'编辑' + titleText" :visible.sync="editDialogVisible" width="30%" @close="editDialogClose()">
      <el-form :model="editForm" ref="editFormRef" label-width="100px">
        <el-form-item label="参数名称：" prop="attr_name">
          <el-input type="text" v-model="editForm.attr_name" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      cateList: [],
      selectedKeys: [],
      cateProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      activeName: 'many',
      manyDataList: [],
      onlyDataList: [],
      // 添加对话框的显示与隐藏
      addDialogVisible: false,
      addForm: {
        attr_name: ''
      },
      // 编辑对话框
      editDialogVisible: false,
      editForm: {}
    }
  },
  created () {
    this.getCateList()
  },
  methods: {
    // 获取商品分类列表
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return
      this.cateList = res.data
    },
    async getParamsList () {
      if (this.selectedKeys.length < 3) {
        this.selectedKeys = []
        return
      }
      const { data: res } = await this.$http.get(`categories/${this.getCateId}/attributes`, {
        params: { sel: this.activeName }
      })
      if (res.meta.status !== 200) return this.$message.error('获取数据列表失败')
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals.trim() ? item.attr_vals.split(',') : []
        // 给每一行的数据添加属性
        item.inputVisible = false
        item.inputValue = ''
      })
      console.log(res.data)
      if (this.activeName === 'many') {
        this.manyDataList = res.data
      } else {
        this.onlyDataList = res.data
      }
    },
    handleChange () {
      this.getParamsList()
    },
    handleTabClick () {
      this.getParamsList()
    },
    // 显示添加对话框
    showDialog () {
      this.addDialogVisible = true
    },
    // 添加属性
    async addParams () {
      const { data: res } = await this.$http.post(`categories/${this.getCateId}/attributes`,
        { attr_name: this.addForm.attr_name, attr_sel: this.activeName })
      if (res.meta.status !== 201) return this.$message.error('添加参数失败')
      this.$message.success('添加成功')
      this.getParamsList()
      this.addDialogVisible = false
    },
    // 监听添加对话框关闭事件
    addDialogClose () {
      this.$refs.addFormRef.resetFields()
    },
    async editDialog (id) {
      const { data: res } = await this.$http.get(`categories/${this.getCateId}/attributes/${id}`)
      if (res.meta.status !== 200) return
      this.editDialogVisible = true
      this.editForm = res.data
    },
    editDialogClose () {
      this.$refs.editFormRef.resetFields()
    },
    // 修改属性
    async editParams () {
      const { data: res } = await this.$http.put(`categories/${this.getCateId}/attributes/${this.editForm.attr_id}`,
        { attr_name: this.editForm.attr_name, attr_sel: this.activeName })
      if (res.meta.status !== 200) return this.$message.error('修改数据失败')
      this.$message.success('更新数据成功')
      this.editDialogVisible = false
      this.getParamsList()
    },
    // 删除参数
    async removeParam (id) {
      const confirmRes = await this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch((err) => { return err })
      if (confirmRes !== 'confirm') return this.$message.error('取消了删除操作')
      const { data: res } = await this.$http.delete(`categories/${this.getCateId}/attributes/${id}`)
      if (res.meta.status !== 200) return this.$message.error('删除失败')
      this.$message.success('删除成功')
      this.getParamsList()
    },
    // 添加/删除tag项
    async optionTag (row) {
      const { data: res } = await this.$http.put(`categories/${this.getCateId}/attributes/${row.attr_id}`,
        { attr_name: row.attr_name, attr_sel: row.attr_sel, attr_vals: row.attr_vals.join(',') })
      if (res.meta.status !== 200) return this.$message.error('修改参数项失败')
      this.$message.success('修改参数项成功')
    },
    // 按回车键或者失去焦点触发的事件
    handleInputConfirm (row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      this.optionTag(row)
      // this.getParamsList()
    },
    // 显示输入框
    showInput (row) {
      // 显示输入文本框
      row.inputVisible = true
      // 自动获取焦点
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
      console.log(row)
    },
    // 删除tag项
    deleteTag (index, row) {
      row.attr_vals.splice(index, 1)
      this.optionTag(row)
    }
  },
  computed: {
    isBtnDisabled () {
      if (this.selectedKeys.length !== 3) {
        return true
      }
      return false
    },
    getCateId () {
      if (this.selectedKeys.length === 3) {
        return this.selectedKeys[2]
      }
      return null
    },
    titleText () {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    }
  }
}
</script>

<style lang="less" scoped>
.cate-opt {
  margin: 15px 0;
}
.el-tag{
  margin: 0 10px;
}
.tag-input{
  width:120px;
}
</style>
